package com.water.devtool.ui.define;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.water.devtool.ITableUtil;
import com.water.devtool.TableUtilFactory;
import com.water.devtool.bean.FieldDefine;
import com.water.devtool.constant.DbType;
import com.water.devtool.define.EntityBean;
import com.water.devtool.ui.UiUtil;
import com.watermud.util.Function;
import com.watermud.util.IteratorContext;
import com.watermud.util.IteratorUtil;

public class ColumnEditComposite extends Composite {
	final static Logger log = LoggerFactory.getLogger(ColumnEditComposite.class);

	private EntityBean entity;
	private Table table;

	/**
	 * Create the composite.
	 * 
	 * @param parent
	 * @param style
	 */
	public ColumnEditComposite(Composite parent, int style) {
		super(parent, style);

		Button btnNewButton = new Button(this, SWT.NONE);
		btnNewButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (entity.getProject().getDbConfig() == null) {
					MessageDialog.openInformation(parent.getShell(), "提示", "请先配置数据库连接!");
					return;
				}
				DbType dbType = entity.getProject().getDbConfig().getDbType();
				final ITableUtil util = TableUtilFactory.create(dbType);
				log.debug("创建数据库工具类：{}",util.getClass());
				String tableName = entity.getCode();
				if ("1".equals(entity.getProject().getDbConfig().getTableNameLowerCase())) {
					tableName = tableName.toLowerCase();
				}
				try {
					List ls = util.getAllColumn(tableName);
					List<FieldDefine> oldList = entity.getColumns();
					entity.setColumns(new ArrayList<FieldDefine>());
					IteratorUtil.iterate(ls, new Function<Map>() {
						@Override
						public void execute(IteratorContext context, Map m) {
							// FIXME 获取字符串长度，用于生成jsp页面长度判断
							FieldDefine fd = util.columnToField(m);
							FieldDefine oldFd = getOldFieldDefine(oldList,fd.getDbName());
							if(oldFd!=null) {
								fd.setInsertAble(oldFd.getInsertAble());
								fd.setUpdateAble(oldFd.getUpdateAble());
								fd.setCondition(oldFd.getCondition());
								fd.setVisiable(oldFd.getVisiable());
								fd.setLabel(oldFd.getLabel());
								fd.setComment(oldFd.getComment());
								fd.setCodeType(oldFd.getCodeType());
							}
							entity.addColumn(fd);
						}

						private FieldDefine getOldFieldDefine(List<FieldDefine> oldList, String dbName) {
							for (FieldDefine fd : oldList) {
								if(fd.getDbName().equals(dbName)) {
									return fd;
								}
							}
							return null;
						}
					});
					loadTableData();
				} catch (Exception e2) {
					MessageDialog.openInformation(parent.getShell(), "异常", "获取表结构失败！"+e2.getMessage());
				}
				
			}
		});
		btnNewButton.setBounds(115, 536, 98, 30);
		btnNewButton.setText("重新加载");

		Button btnNewButton_1 = new Button(this, SWT.NONE);
		btnNewButton_1.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
			}
		});
		btnNewButton_1.setBounds(328, 536, 98, 30);
		btnNewButton_1.setText("添加");

		Button btnNewButton_2 = new Button(this, SWT.NONE);
		btnNewButton_2.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				closeTab();
			}
		});
		btnNewButton_2.setBounds(967, 536, 98, 30);
		btnNewButton_2.setText("关闭");

		Button button = new Button(this, SWT.NONE);
		button.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				int count = table.getItemCount();
				List<FieldDefine> fs = new ArrayList<FieldDefine>();
				for (int i = 0; i < count; i++) {
					TableItem item = table.getItem(i);
					FieldDefine fd = new FieldDefine();
					fd.setDbName(item.getText(0));
					fd.setDbType(item.getText(1));
					fd.setName(item.getText(2));
					fd.setJavaType(item.getText(3));
					fd.setCharLen(item.getText(4));
					fd.setCodeType(item.getText(5));
					fd.setComment(item.getText(6));

					fd.setInsertAble(getSelectValue(item, 7));
					fd.setUpdateAble(getSelectValue(item, 8));
					fd.setCondition(getSelectValue(item, 9));
					fd.setVisiable(getSelectValue(item, 10));
					fd.setLabel(item.getText(11));
					fd.setLongChar(item.getText(12));
					fd.setNotNullAble(getSelectValue(item, 13));
					fs.add(fd);
				}
				entity.setColumns(fs);
			}
		});
		button.setText("确定");
		button.setBounds(754, 536, 98, 30);

		Button button_1 = new Button(this, SWT.NONE);
		button_1.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				int i = table.getSelectionIndex();
				table.remove(i);
			}
		});
		button_1.setText("删除");
		button_1.setBounds(541, 536, 98, 30);

	}
	
	

	private String getSelectValue(TableItem item, int index) {
		Boolean select = (Boolean) item.getData(String.valueOf(index));
		if (select == null) {
			return item.getText(index);
		}
		return select ? "1" : "0";
	}

	protected void loadTableData() {
		table.removeAll();
		List<FieldDefine> temp = entity.getColumns();
		for (FieldDefine column : temp) {
			TableItem item = new TableItem(table, SWT.NONE);
			String[] param = new String[] { column.getDbName(), column.getDbType(), column.getName(),
					column.getJavaType(), column.getCharLen(), column.getCodeType(), column.getComment(),
					column.getInsertAble(), column.getUpdateAble(), column.getCondition(), column.getVisiable(),
					column.getLabel(), column.getLongChar(),column.getNotNullAble() };
			item.setText(param);

			addOneCheckItem(item, 7, column.getInsertAble().equals("1"));
			addOneCheckItem(item, 8, column.getUpdateAble().equals("1"));
			addOneCheckItem(item, 9, column.getCondition().equals("1"));
			addOneCheckItem(item, 10, column.getVisiable().equals("1"));
			addOneCheckItem(item, 13, "1".equals(column.getNotNullAble()));

		}

	}

	private void addOneCheckItem(TableItem item, int index, boolean checked) {
		TableEditor editor = new TableEditor(table);
		editor.grabHorizontal = editor.grabVertical = true;
		editor.horizontalAlignment = SWT.CENTER;
		Button btn = new Button(table, SWT.CHECK);
		btn.setSelection(checked);
		item.setData(String.valueOf(index), checked);
		editor.setEditor(btn, item, index);
		btn.setAlignment(SWT.CENTER);
		btn.addSelectionListener(new SelectionListener() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				item.setData(String.valueOf(index), btn.getSelection());
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent arg0) {
				item.setData(String.valueOf(index), btn.getSelection());
			}
		});
	}

	public void closeTab() {
		TabFolder tabFolder = (TabFolder) getParent();
		TabItem[] items = tabFolder.getSelection();
		for (TabItem tabItem : items) {
			tabItem.dispose();
		}
	}

	// 创建表格
	private void createTable() {
		// 表格布局
		GridData gridData = new org.eclipse.swt.layout.GridData();
		gridData.horizontalAlignment = SWT.LEFT;
		gridData.grabExcessHorizontalSpace = true;
		gridData.grabExcessVerticalSpace = true;
		gridData.verticalAlignment = SWT.FILL;

		// 创建表格，使用SWT.FULL_SELECTION样式，可同时选中一行
		table = new Table(this, SWT.FULL_SELECTION);
		table.setBounds(10, 10, 1000, 500);
		table.setHeaderVisible(true);// 设置显示表头
		table.setLinesVisible(true);// 设置显示表格线/*
		// 创建表头的字符串数组
		String[] tableHeader = { "字段名", "数据库类型", "Java名称", "Java类型", "长度", "数据字典", "注释", "插入", "更新",
				"查询", "显示", "名称", "条件", "不可为空" };
		int[] widths = { 75, 75, 75, 75, 75, 60, 100, 40, 40, 40, 40, 100, 100, 80, 80  };
		for (int i = 0; i < tableHeader.length; i++) {
			TableColumn tableColumn = new TableColumn(table, SWT.NONE);
			tableColumn.setText(tableHeader[i]);
			// 设置表头可移动，默认为false
			tableColumn.setMoveable(false);
			tableColumn.setWidth(widths[i]);
			if (i >= 7 && i <= 10) {
				tableColumn.setAlignment(SWT.CENTER);
			}
		}
		loadTableData();

		UiUtil.setTableEditor(table, tableHeader);

		// ******************************************************/
	}

	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}

	public void setEntity(EntityBean entity) {
		this.entity = entity;
		createTable();
	}

}
